package cn.sc.summer.summerboot.runner;

import cn.sc.summer.constant.sms.SmsConstant;
import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.core.runner.ServerCommonRunner;
import cn.sc.summer.domain.service.RunnerService;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.thread.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * 类名：服务启动后执行的操作类
 *
 * @author a-xin
 * @date 2023/8/25 14:31
 */
@Slf4j
@Component
public class SysRunner extends ServerCommonRunner {

    @Resource
    private ThreadUtil threadUtil;

    @Resource
    private RunnerService runnerService;

    /**
     * 初始化完成后执行逻辑(服务启动指定间隔内不执行)
     *
     * @param args 参数
     */
    @Override
    protected void startRunComplete(String... args) {
        //缓存用户信息
        CompletableFuture<Void> userInfoFuture = CompletableFuture.runAsync(() -> runnerService.cacheUserInfo(), threadUtil.THREAD_POOL());

        //缓存短信模版
        CompletableFuture<Void> smsTemplateFuture = CompletableFuture.runAsync(() -> runnerService.cacheSmsTemplate(), threadUtil.THREAD_POOL());

        CompletableFuture.allOf(userInfoFuture, smsTemplateFuture)
                .whenComplete((result, exception) -> {
                    log.info("==> The user information and sms template are cached！");
                }).join();
    }

    /**
     * 初始化完成后执行逻辑
     *
     * @param args 参数
     */
    @Override
    protected void startRun(String... args) {
    }

    /**
     * 如果该实例为最后一个实例，则执行摧毁逻辑
     *
     * @param event spring容器关闭事件信息
     */
    @Override
    protected void lastDestroy(@NonNull ContextClosedEvent event) {
        RedisHelper.delKeysByPrefix(TokenConstant.USER_INFO,
                SmsConstant.SMS_TEMPLATE);
    }

    /**
     * 默认执行的摧毁逻辑
     *
     * @param event spring容器关闭事件信息
     */
    @Override
    protected void destroy(@NonNull ContextClosedEvent event) {

    }

}
